import {Injectable} from '@angular/core';
import {Observable} from 'rxjs/Observable';
import {Headers, Http} from '@angular/http';
import {Phase} from '../entity/phase.model';
import {AppConfig} from '../config';
import {InterceptorService} from './interceptor/interceptor-service';

@Injectable()
export class PhaseService {
  private readonly param = 'phases';

  private get url(): string {
    return `${AppConfig.APP_RESTFUL}/${this.param}`;
  }

  constructor(private http: InterceptorService) {
  }

  getPhases(): Promise<Phase[]> {
    return this.http.get(this.url)
      .toPromise()
      .then(response => response.data as Phase[])
      .catch(this.handleError);

  }


  getPhasesByfarmId(farmId: number): Promise<Phase[]> {
    return this.http.get(`${this.url}/farm/${farmId}`)
      .toPromise()
      .then(response => {
        return response.code === '200' ? response.data as Phase[] : [];
      })
      .catch(this.handleError);

  }


  getPhaseByphaseID(phaseId: number): Promise<Phase[]> {
    return this.http.get(`${this.url} ${phaseId}`)
      .toPromise()
      .then(response => response.code === '200' ? response.data as Phase[] : [])
      .catch(this.handleError);
  }

  create(Phase: Phase): Promise<Phase> {
    return this.http.post(this.url, JSON.stringify(Phase))
      .toPromise()
      .then(res => {
        try {
          let result = res;
          switch (result.code) {
            case '200':
              return result.data as Phase;
            case '-1':
              throw new Error(result.message);
          }
        }
        catch (error) {
          this.handleError(error);
        }
      })
      .catch(this.handleError);
  }

  update(phase: Phase): Promise<Phase> {
    const url = `${this.url}`;
    return this.http.put(url, JSON.stringify(phase))
      .toPromise()
      .then(() => phase)
      .catch(this.handleError);
  }

  //根据PhaseCode判断是否已经存在
  hasPhaseCode(phaseCode: string, farmId: number, phaseId: number): Observable<boolean> {
    const url = `${this.url}/phaseCode/${phaseCode}/farmId/${farmId}/phaseId/${phaseId}`;
    // const url = `http://192.168.150.3:8585/webapi/v1/phases/phaseCode/${phaseCode}/farmId/${farmId}/phaseId/${phaseId}`
    return this.http.get(url).map(response => {
      let code = response.code;
      switch (code) {
        case '3001':
          return true;
        case '3002':
          return false;
      }
    }).catch(this.handleError);
  }

  //根据phaseName判断是否已经存在
  hasPhaseName(phaseName: string, farmId: number, phaseId: number): Observable<boolean> {
    const url = `${this.url}/phaseName/${phaseName}/farmId/${farmId}/phaseId/${phaseId}`;
    return this.http.get(url).map(response => {
      let code = response.code;
      switch (code) {
        case '3001':
          return true;
        case '3002':
          return false;
      }
    }).catch(this.handleError);
  }

  //根据simpleCode判断是否已经存在
  // hasSimpleCode(simpleCode: string, farmId: number): Observable<boolean> {
  //     const url = `${this.url}/simpleCode/${simpleCode}/farmId/${farmId}`;
  //     return this.http.get(url).map(response => {
  //       let code = response.code;
  //       switch (code) {
  //         case "3001":
  //           return true;
  //         case "3002":
  //           return false;
  //       }
  //     }).catch(this.handleError);
  //   }


  delete(id: number): Promise<void> {
    const url = `${this.url}/${id}`;
    return this.http.delete(url)
      .toPromise()
      .then(() => null)
      .catch(this.handleError);
  }

  batchDelete(valueIds: number[]): Promise<boolean> {
    const apiUrl = `${this.url}?items=${valueIds}`;
    return this.http.delete(apiUrl)
      .toPromise()
      .then(response => {
        try {
          let result = response;
          switch (result.code) {
            case '200':
              return true;
            case '-1':
              throw new Error(result.message);
          }
        }
        catch (error) {
          throw error;
        }

      })
      .catch(this.handleError);
  }


  private handleError(error: any): Promise<any> {
    // console.error('An error occurred', error); // for demo purposes only
    return Promise.reject(error.message || error);
  }


}


